package com.zc.asyn;

import com.zc.common.Constant;
import com.zc.common.Shop;
import org.springframework.util.StopWatch;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 异步的方式
 * 2019年12月15日 02:37:53
 */
public class AsynTest {

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(50);


        List<Shop> asynShops = new ArrayList<>();


        for (int i = 1; i <= Constant.COUNT; i++) {
            asynShops.add(new Shop());
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();


        List<CompletableFuture<Integer>> futures = asynShops.stream()
                .map(asynShop -> CompletableFuture.supplyAsync(() -> asynShop.sleep(), executorService)
                ).collect(Collectors.toList());

        /*归并结果*/
        List<Integer> results = futures.stream().filter(future -> null != future.join()).map
                (CompletableFuture::join).collect(Collectors.toList());
        executorService.shutdown();

        stopWatch.stop();

        System.out.println("花费总时间 totalTime = " + stopWatch.getTotalTimeMillis());
        System.out.println("返回结果总条数为 totalCount = " + results.size());
        System.out.println("返回结果结果为  results = " + results.toString());

    }






}
